<script>
	import {
		getBdcRoute
	} from '@/api/mall.js';
	import navBar from "@/components/layout/navbar/index.vue";
	import {
		mapState
	} from 'vuex';

	export default {
		name: "list",
		components: {
			navBar
		},
		data() {
			return {
				// 当前选中的线路索引
				currentTabIndex: 0,

				// 线路列表
				routesList: [],

				// 是否展开站点信息
				isStationsExpanded: true,

				// 线路基础信息
				currentRoute: null,

				// 查询参数
				queryParams: {
					pageNo: 1,
					pageSize: 10
				},

				// 加载状态
				loading: true,

				// 线路数据 (从config.js移过来)
				routesData: {
					// 全部景区（默认）
					0: []
				}
			}
		},
		watch: {
			'$i18n.locale'() {
				// 监听语言变化，重新设置导航栏标题
				this.setNavigationTitle();
			}
		},
		computed: {
			...mapState({
				selectedLocation: state => state.base.selectedLocation
			}),
		},
		onLoad() {
			// 设置导航栏标题
			this.setNavigationTitle();
			// 获取线路数据
			this.fetchRouteData();
			if (this.selectedLocation.value === 0) {
				this.selectLocation()
			}
		},
		onReady() {
			// 页面渲染完成后，确保数据已加载
			if (this.routesList.length === 0 && Object.keys(this.routesData).length > 1) {
				this.loadRoutesList();
			}
		},
		methods: {
			// 从接口获取线路数据
			async fetchRouteData() {
				try {
					const res = await getBdcRoute();
					if (res && res.Data) {
						// 解析返回的JSON字符串为对象
						let data = JSON.parse(res.Data);
						console.log("路线信息 data =>", data);
						// 确保存在0:[]项
						if (!data[0]) {
							data[0] = [];
						}

						this.routesData = data;
						this.loadRoutesList();
					} else {
						console.error('获取线路数据失败:', res);
						uni.showToast({
							title: this.$t('traffic.list.loadDataFailed'),
							icon: 'none'
						});
					}
				} catch (error) {
					console.error('获取线路数据异常:', error);
					uni.showToast({
						title: this.$t('traffic.list.networkError'),
						icon: 'none'
					});
				}
			},

			// 根据区域ID和路线ID获取路线 (从config.js移过来)
			getRouteById(locationId, routeId) {
				const locationRoutes = this.routesData[locationId] || [];
				const route = locationRoutes.find(route => route.id === parseInt(routeId));
				return route || (locationRoutes[0] || null);
			},

			// 获取指定区域的所有路线 (从config.js移过来)
			getRoutesByLocation(locationId) {
				return this.routesData[locationId] || [];
			},

			// 调用导航栏的选择位置方法
			selectLocation() {
				if (this.$refs.navBarRef) {
					this.$refs.navBarRef.showCustomAction();
				}
			},

			// 加载线路列表
			async loadRoutesList() {
				this.loading = true;

				try {
					// 从本地数据获取当前选中区域的数据
					const locationId = this.selectedLocation.value;
					this.routesList = this.getRoutesByLocation(locationId);
					console.log("routesList =>", this.routesList);
					// 如果有线路数据，默认选中第一条
					if (this.routesList.length > 0) {
						this.currentTabIndex = 0;
						this.currentRoute = this.routesList[0];
					} else {
						this.currentRoute = null;
					}

					// 延迟关闭加载状态，确保DOM更新
					setTimeout(() => {
						this.loading = false;
					}, 500);
				} catch (error) {
					console.error("加载线路列表失败:", error);
					uni.showToast({
						title: this.$t('traffic.list.loadFailed'),
						icon: 'none'
					});
					this.loading = false;
				}
			},

			// 切换线路
			switchTab(index) {
				if (this.currentTabIndex === index) return;

				this.currentTabIndex = index;
				if (this.routesList && this.routesList.length > index) {
					this.currentRoute = this.routesList[index];
				}

				// 重置站点展开状态
				this.isStationsExpanded = true;
			},

			// 展开/折叠站点信息
			toggleStations() {
				this.isStationsExpanded = !this.isStationsExpanded;
			},

			// 查看交通图
			viewTrafficMap() {
				uni.openEmbeddedMiniProgram({
					appId: "wx76a6823f3bb55d2b"
				})
			},

			// 订票
			orderTicket() {
				if (!this.currentRoute) return;

				console.log("跳转到订票页面，线路ID：", this.currentRoute.id);
				console.log(this.currentRoute);
				let url = '';
				console.log(this.currentRoute.isPack, !!this.currentRoute.isPack);

				if (this.currentRoute.isPack) {
					uni.navigateTo({
						url: `/mall_subpages/goods/package?id=${this.currentRoute.productId}`
					})

					return;
				}
				// 将当前路线数据编码后传递
				const routeData = encodeURIComponent(JSON.stringify(this.currentRoute));

				// uni.navigateTo({
				//   url: `/ticket_subpages/traffic/buyTickets?id=${this.currentRoute.id}&locationId=${this.selectedLocation.value}&routeData=${routeData}`
				// });
				uni.navigateTo({
					url: `/ticket_subpages/traffic/mpBuyTickets?id=${this.currentRoute.id}&locationId=${this.selectedLocation.value}`
				});
			},

			locationChanged() {
				this.loadRoutesList()
			},

			// 设置导航栏标题
			setNavigationTitle() {
				uni.setNavigationBarTitle({
					title: this.$t('traffic.list.title')
				});
			}
		}
	}
</script>

<template>
	<view class="traffic-container">
		<!-- 顶部选项卡 -->
		<view class="tabs-container">
			<nav-bar ref="navBarRef" title="摆渡车购票" :allowMaskClose="false" showHeaderIcon
				@locationChanged="locationChanged" />
			<view v-if="selectedLocation.value === 0" class="no-data-tip">
				{{$t('traffic.list.selectAreaTip')}}
			</view>
			<view v-else-if="routesList.length > 0">
				<scroll-view class="tabs-scroll" scroll-x>
					<view class="tabs">
						<view v-for="(route, index) in routesList" :key="route.id" class="tab-item"
							:class="{'active': currentTabIndex === index}" @click="switchTab(index)">
							<text>{{route.name}}</text>
						</view>
					</view>
				</scroll-view>
			</view>
			<view v-else class="no-data-tip">
				{{$t('traffic.list.noRouteData')}}
			</view>
		</view>

		<!-- 加载中 -->
		<view class="loading-container" v-if="loading">
			<view class="loading-icon"></view>
			<text>{{$t('traffic.list.loading')}}</text>
		</view>

		<!-- 线路信息 -->
		<scroll-view class="route-content" scroll-y :scroll-with-animation="true" v-if="currentRoute && !loading">
			<!-- 线路基本信息卡片 -->
			<view class="route-info-card">
				<view style="border-right: 1px solid #b1b1b1; flex: 2">
					<view class="route-header">
						<view class="route-title">
							<text class="name">{{currentRoute.name}}</text>
						</view>
					</view>

					<view class="price-info">
						<text class="price-text">{{$t('traffic.list.oneWayPrice', {price: currentRoute.price})}}</text>
					</view>

					<view class="schedule-info">
						<view class="season-schedule" v-if="currentRoute.firstBusTime">
							<text>{{currentRoute.firstBusTime}}</text>
						</view>
						<view class="season-schedule" v-if="currentRoute.lastBusTime">
							<text>{{currentRoute.lastBusTime}}</text>
						</view>
					</view>

					<view class="route-details">
						<view class="detail-item" v-if="currentRoute.interval">
							<text class="label">{{$t('traffic.list.busInterval')}}:</text>
							<text class="value">{{currentRoute.interval}}</text>
						</view>
						<view class="detail-item" v-if="currentRoute.specialNote">
							<text class="label">{{$t('traffic.list.specialNote')}}:</text>
							<text class="value">{{currentRoute.specialNote}}</text>
						</view>
						<view class="detail-item" v-if="currentRoute.notes">
							<text class="label">{{$t('traffic.list.remarks')}}:</text>
							<text class="value">{{currentRoute.notes}}</text>
						</view>
						<view class="detail-item" v-if="currentRoute.extraInfo">
							<text class="label">{{$t('traffic.list.extraInfo')}}:</text>
							<text class="value">{{currentRoute.extraInfo}}</text>
						</view>
					</view>

					<!-- 特殊服务说明 -->
					<view class="special-service-info" v-if="currentRoute.isSpecialService">
						<view v-if="currentRoute.specialServiceType === 'carRental'">
							<view class="service-title">{{$t('traffic.list.carRentalTitle')}}</view>
							<view class="service-desc">{{$t('traffic.list.carRentalDesc')}}</view>
						</view>
						<view v-else-if="currentRoute.specialServiceType === 'weddingCar'">
							<view class="service-title">{{$t('traffic.list.weddingCarTitle')}}</view>
							<view class="service-desc">{{$t('traffic.list.weddingCarDesc')}}</view>
							<view class="service-notes" v-if="currentRoute.notes && currentRoute.notes.length > 0">
								<view v-for="(note, idx) in currentRoute.notes" :key="idx" class="note-item">
									{{note}}
								</view>
							</view>
						</view>
					</view>
				</view>
				<view style=" flex: 1">
					<view class="view-map-btn" @click="viewTrafficMap(currentRoute)">
						<image src="https://wzws.wanshanlundiao.cn/upload/img/20250512/202505121404589757.png"
							mode="aspectFit"></image>
						<text>{{$t('traffic.list.viewTrafficMap')}}</text>
					</view>
				</view>
			</view>

			<!-- 站点信息展开控制，仅对有站点的线路显示 -->
			<!--      <view class="stations-header" @click="toggleStations" v-if="currentRoute.hasStations">-->
			<!--        <text class="title">线路站点</text>-->
			<!--        <view class="expand-icon" :class="{'expanded': isStationsExpanded}"></view>-->
			<!--      </view>-->

			<!-- 站点时间线 -->
			<view class="stations-timeline" v-if="isStationsExpanded && currentRoute.hasStations">
				<view v-for="(station, index) in currentRoute.stations" :key="station.id" class="station-item" :class="{
            'start-station': station.isStart,
            'end-station': station.isEnd
          }">
					<!-- 站点标记 -->
					<view class="station-marker">
						<view class="dot" :class="{'active': station.isStart || station.isEnd}"></view>
						<view class="line" v-if="index < currentRoute.stations.length - 1"></view>
					</view>

					<!-- 站点信息 -->
					<view class="station-info">
						<view class="station-name">
							<text>{{station.name}}</text>
							<text class="station-tag"
								v-if="station.isStart">({{$t('traffic.list.startStation')}})</text>
							<text class="station-tag" v-if="station.isEnd">({{$t('traffic.list.endStation')}})</text>
						</view>

						<view class="arrival-time" v-if="station.nextArrivalTime">
							{{$t('traffic.list.nextArrival')}}: {{station.nextArrivalTime}}
						</view>
					</view>
				</view>
			</view>

			<!-- 占位，防止底部按钮遮挡内容 -->
			<view class="bottom-placeholder"></view>
		</scroll-view>

		<!-- 底部订票按钮 -->
		<view class="bottom-fixed-container" v-if="currentRoute && !loading">
			<view class="order-btn" @click="orderTicket">
				{{ currentRoute.isSpecialService ? $t('traffic.list.bookService') : $t('traffic.list.bookTicket') }}
			</view>
		</view>

	</view>
</template>

<style scoped lang="scss">
	.traffic-container {
		min-height: 100vh;
		background-color: #f5f5f5;
		display: flex;
		flex-direction: column;
		position: relative;
	}

	/* 顶部选项卡 */
	.tabs-container {
		background-color: #fff;
		position: sticky;
		top: 0;
		z-index: 10;
		box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);

		.tabs-scroll {
			white-space: nowrap;
			height: 100rpx;
		}

		.tabs {
			display: inline-flex;
			height: 100rpx;
			line-height: 100rpx;

			.tab-item {
				padding: 0 40rpx;
				font-size: 30rpx;
				color: #666;
				position: relative;
				transition: all 0.3s ease;

				&.active {
					color: #3a7fe6;
					font-weight: bold;

					&::after {
						content: '';
						position: absolute;
						bottom: 0;
						left: 40rpx;
						right: 40rpx;
						height: 6rpx;
						background-color: #3a7fe6;
						border-radius: 3rpx;
					}
				}
			}
		}
	}

	/* 线路内容区域 */
	.route-content {
		box-sizing: border-box;
		flex: 1;
		padding: 20rpx;
		height: calc(100vh - 100rpx - 130rpx);
	}

	/* 线路基本信息卡片 */
	.route-info-card {
		background-color: #fff;
		border-radius: 12rpx;
		box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
		overflow: hidden;
		padding: 30rpx;
		margin-bottom: 20rpx;
		display: flex;
		align-items: center;

		.route-header {
			display: flex;
			justify-content: space-between;
			align-items: center;
			margin-bottom: 20rpx;

			.route-title {
				flex: 1;

				.name {
					font-size: 38rpx;
					font-weight: bold;
					color: #333;
				}
			}


		}

		.view-map-btn {
			display: flex;
			flex-direction: column;
			align-items: center;
			padding: 10rpx;

			image {
				width: 60rpx;
				height: 60rpx;
				margin-bottom: 15rpx;
			}

			text {
				font-size: 22rpx;
			}
		}

		.price-info {
			margin-bottom: 12rpx;

			.price-text {
				font-size: 22rpx;
				font-weight: 500;
				color: #333;
			}
		}

		.schedule-info {
			margin-bottom: 20rpx;

			.season-schedule {
				font-size: 22rpx;
				color: #666;
				margin-bottom: 6rpx;

				&:last-child {
					margin-bottom: 0;
				}
			}
		}

		.route-details {
			//background-color: #f9f9f9;
			//border-radius: 8rpx;
			//padding: 20rpx;

			.detail-item {
				display: flex;
				margin-bottom: 10rpx;

				&:last-child {
					margin-bottom: 0;
				}

				.label {
					width: 120rpx;
					font-size: 22rpx;
					color: #666;
				}

				.value {
					flex: 1;
					font-size: 22rpx;
					color: #333;
				}
			}
		}
	}

	/* 站点信息展开控制 */
	.stations-header {
		background-color: #fff;
		border-radius: 12rpx;
		box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
		padding: 30rpx;
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 20rpx;

		.title {
			font-size: 32rpx;
			font-weight: bold;
			color: #333;
		}

		.expand-icon {
			width: 40rpx;
			height: 40rpx;
			position: relative;

			&::before,
			&::after {
				content: '';
				position: absolute;
				background-color: #666;
				transition: all 0.3s ease;
			}

			&::before {
				top: 50%;
				left: 0;
				width: 100%;
				height: 4rpx;
				transform: translateY(-50%);
			}

			&::after {
				top: 0;
				left: 50%;
				width: 4rpx;
				height: 100%;
				transform: translateX(-50%);
			}

			&.expanded::after {
				transform: translateX(-50%) scaleY(0);
			}
		}
	}

	/* 站点时间线 */
	.stations-timeline {
		background-color: #fff;
		border-radius: 12rpx;
		box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
		padding: 30rpx;

		.station-item {
			display: flex;
			animation: fadeIn 0.5s ease forwards;
			opacity: 0;
			transform: translateY(10rpx);

			@for $i from 1 through 20 {
				&:nth-child(#{$i}) {
					animation-delay: #{$i * 0.05}s;
				}
			}

			.station-marker {
				width: 60rpx;
				display: flex;
				flex-direction: column;
				align-items: center;

				.dot {
					width: 20rpx;
					height: 20rpx;
					border-radius: 50%;
					background-color: #ccc;
					transition: all 0.3s ease;

					&.active {
						width: 30rpx;
						height: 30rpx;
						background-color: #3a7fe6;
						box-shadow: 0 0 0 6rpx rgba(58, 127, 230, 0.2);
					}
				}

				.line {
					width: 0rpx;
					border: 1rpx dashed #e0e0e0;
					height: 80rpx;
					background-color: #e0e0e0;
					position: relative;
					overflow: hidden;

					&::after {
						content: '';
						position: absolute;
						top: 0;
						left: 0;
						width: 100%;
						height: 100%;
						background-color: #3a7fe6;
						border: 1rpx dashed #3a7fe6;
						transform: translateY(-100%);
						animation: lineGrow 1s ease forwards;
					}
				}
			}

			.station-info {
				flex: 1;
				padding-left: 20rpx;

				.station-name {
					font-size: 28rpx;
					color: #333;
					margin-bottom: 5rpx;
					font-weight: 500;
					transition: all 0.3s ease;
				}

				.station-tag {
					font-size: 24rpx;
					color: #3a7fe6;
					margin-left: 10rpx;
					font-weight: normal;
					display: inline-block;
					padding: 0 10rpx;
					background-color: rgba(58, 127, 230, 0.1);
					border-radius: 4rpx;
				}

				.arrival-time {
					font-size: 24rpx;
					color: #999;
				}
			}

			&.start-station .station-info .station-name,
			&.end-station .station-info .station-name {
				color: #3a7fe6;
				font-weight: bold;
				transform: scale(1.05);
				transform-origin: left center;
			}
		}
	}

	/* 底部固定订票按钮 */
	.bottom-fixed-container {
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		height: 130rpx;
		background: linear-gradient(transparent, rgba(255, 255, 255, 0.8) 20%, #fff 40%);
		display: flex;
		align-items: center;
		justify-content: center;
		padding: 0 30rpx;

		.order-btn {
			width: 100%;
			height: 90rpx;
			line-height: 90rpx;
			background: linear-gradient(90deg, #3a7fe6, #5895e9);
			border-radius: 45rpx;
			text-align: center;
			color: #fff;
			font-size: 32rpx;
			font-weight: bold;
			box-shadow: 0 4rpx 15rpx rgba(58, 127, 230, 0.3);
			transition: all 0.2s ease;

			&:active {
				transform: scale(0.96);
				box-shadow: 0 2rpx 8rpx rgba(58, 127, 230, 0.2);
			}
		}
	}

	.bottom-placeholder {
		height: 150rpx;
	}

	/* 加载状态 */
	.loading-container {
		flex: 1;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		padding: 50rpx 0;

		.loading-icon {
			width: 60rpx;
			height: 60rpx;
			border: 4rpx solid #f3f3f3;
			border-top: 4rpx solid #3a7fe6;
			border-radius: 50%;
			animation: rotate 1s linear infinite;
		}

		text {
			margin-top: 20rpx;
			font-size: 28rpx;
			color: #999;
		}
	}

	@keyframes rotate {
		from {
			transform: rotate(0deg);
		}

		to {
			transform: rotate(360deg);
		}
	}

	@keyframes fadeIn {
		from {
			opacity: 0;
			transform: translateY(10rpx);
		}

		to {
			opacity: 1;
			transform: translateY(0);
		}
	}

	@keyframes lineGrow {
		from {
			transform: translateY(-100%);
		}

		to {
			transform: translateY(0);
		}
	}

	/* 特殊服务说明 */
	.special-service-info {
		//background-color: #f9f9f9;
		//border-radius: 8rpx;
		//padding: 20rpx;
		margin-top: 20rpx;

		.service-title {
			font-size: 30rpx;
			font-weight: bold;
			color: #333;
			margin-bottom: 10rpx;
		}

		.service-desc {
			font-size: 28rpx;
			color: #666;
			margin-bottom: 15rpx;
		}

		.service-notes {
			.note-item {
				font-size: 26rpx;
				color: #666;
				padding: 5rpx 0;
				position: relative;
				padding-left: 10rpx;

				&:before {
					content: '';
					position: absolute;
					left: 0;
					top: 18rpx;
					width: 6rpx;
					height: 6rpx;
					border-radius: 50%;
					background-color: #666;
				}
			}
		}
	}

	.no-data-tip {
		text-align: center;
		color: #999;
		font-size: 30rpx;
		padding: 40rpx 0 20rpx 0;
	}
</style>